<?php

namespace app\controller;

use think\facade\Db;
use app\model\Recharge;
use app\model\Customer;
use app\model\OpAccount;
use app\model\Claim;
use app\model\ViewAccRefund;
use app\model\User;
use think\facade\View;
use app\model\Items;
use think\Model;
use app\model\AccRefund;
use app\model\Channel;
use app\model\ReturnedMoney;
use app\model\ViewItemInfo;
use app\model\AccItem;
use app\model\ItemConsume;
use app\model\ViewItemsInfo;
use app\model\Industry;
use app\model\ChannelRecharge;
use app\model\AccTransfer;
use app\controller\QywxApi;
use app\model\WxGroup;
/**
 * 财务模块
 */
class Finance
{

    /**
     * 客户打款
     */
    public function customer_recharge(Recharge $Recharge) 
    {
        $user = new User();
        if(request()->isPost() && input('t')=='json'){
            $arr = $Recharge->get_list_apply_re(input('post.'),1);
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }

        $cu_list = Customer::field('id,name')->select();
        $m_list = $user->get_role_list('14,19');
        return view('', ['cu_list'=>$cu_list,'m_list'=>$m_list]);
    }

    /**
     * 客户退款
     */
    public function customer_refund(Recharge $Recharge)
    {
        if(request()->isPost() && input('t')=='json'){
            $arr = $Recharge->get_list_cu_refund(input('post.'));
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }
    
        $cu_list = Customer::field('id,name')->select();
        $data = ['cu_list'=>$cu_list];
        return view('', ['cu_list'=>$cu_list]);
    }
    /**
     * 客户欠款
     */
    public function customer_advance(User $user){
        $customer = new Customer();
        if(request()->isPost() && input('t') == 'json'){
            $p = input("post.");
            if(isset($p['id']) && !empty($p['id'])){
                $w[] = ['cu.id','=',$p['id']];
            }else{
                $wh[] = ['is_advance','=',1];
                $wh[] = ['type','=',1];
                $customer_ids = Recharge::where($wh)->group('customer_id')->column('customer_id');
                $w[] = ['cu.id','in',$customer_ids];
            }
            if(isset($p['media_id']) && !empty($p['media_id'])){
                $w[] = ['cu.user_id','=',$p['media_id']];
            }
            
            $list = $customer
            ->alias('cu')->field('cu.*,u.username')
            ->join('user u','cu.user_id = u.id')
            ->where($w)->order("cu.create_time desc")->page($p['page']*1,$p['limit']*1)->select();
            foreach ($list as $k =>$v) {
                $list[$k]['advance'] = $this->get_cu_advance($v['id']);
            } 
            $con = $customer->alias('cu')->where($w)->count("cu.id");
            
            return json(['code'=>0,'msg'=>'','count'=>$con,'data'=>$list]);
        }
        $cu_list = Customer::select();
        $media_list = $user->get_role_list('14,19');

        View::assign('cu_list',$cu_list);
        View::assign('media_list',$media_list);
        return view();
    }
    // 获取客户欠款
    function get_cu_advance($customer_id){
        $wh[] = ['is_advance','=',1];
        $wh[] = ['type','=',1];
        $wh[] = ['status','=',1];
        $wh[] = ['customer_id','=',$customer_id];
        return Recharge::where($wh)->sum('amount');
    }
    //获取有客户的备款
    public function customer_ready(Customer $Customer,User $user){
        if(request()->isPost() && input('t') == 'json'){
            $data = input('post.');
            if(isset($data['id']) && !empty($data['id'])){
                $wh[] = ['cu.id','=',$data['id']];
            }
            if(isset($data['media_id']) && !empty($data['media_id'])){
                $wh[] = ['cu.user_id','=',$data['media_id']];
            }

            //$wh[] = ['cu.prepare_money','>',0];
            $wh[] = ['cu.id','>',0];
            $list = $Customer->alias("cu")
            ->field("cu.*,u.username")
            ->join('user u','cu.user_id = u.id')
            ->where($wh)->order('cu.prepare_money')->page($data['page']*1,$data['limit']*1)->select();
            $con = $Customer->alias("cu")->where($wh)->count('id');
            
            return json(['code'=>0,'msg'=>'','count'=>$con,'data'=>$list]);
        }
        $cu_list = Customer::select();
        $media_list = $user->get_role_list('14,19');

        View::assign('cu_list',$cu_list);
        View::assign('media_list',$media_list);
        return view();
    }
    //客户打款回滚
    public function return_customer_money(){ 
        if(request()->isPost() && input('t')=='json'){
            $id = input('post.id');
            $rs = Recharge::find($id);
            // 启动事务
            Db::startTrans();
            try {
                if($rs['amount'] > 0 ){
                    Db::name('customer')->where('id', $rs['customer_id'])->dec('prepare_money',$rs['amount'])->update();
                    Db::name('customer')->where('id', $rs['customer_id'])->dec('total_recharge',$rs['amount'])->update();
                }else{
                    Db::name('customer')->where('id', $rs['customer_id'])->inc('prepare_money',$rs['amount'])->update();
                    Db::name('customer')->where('id', $rs['customer_id'])->inc('total_recharge',$rs['amount'])->update();
                }
                
                $da['id'] =  $id;
                $da['status'] = 0;
                Db::name('recharge')->update($da);
                // 提交事务
                Db::commit();
                log_add(2, '财务回滚操作');
                
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
            
    }
    

    /**
     * 财务充值
     */
    public function account_recharge(Recharge $Recharge)
    {
        $user = new User();
        if(request()->isPost() && input('t')=='json'){
            $arr = $Recharge->get_list_apply_re(input('post.'),2);
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }

        $acc_list = OpAccount::field('id,name_id')->select();
        $cu_list = Customer::field('id,name')->select();
        $m_list = $user->get_role_list('14,19');
        $arr['channel'] = Channel::field('id,name')->select();
        $arr['industry'] = Industry::field('id,name')->select();
        $arr['items'] = Items::field('id,name')->select();

        View::assign('acc_list',$acc_list);
        View::assign('cu_list',$cu_list);
        View::assign('m_list',$m_list);
        View::assign('arr',$arr);
        return view(); 
    }

    /**
     * 财务账户退款
     */
    public function account_refund(ViewAccRefund $ViewAccRefund,User $user,Recharge $Recharge)
    {
        if(request()->isPost() && input('t')=='json'){
            //$arr = $ViewAccRefund->get_cw_refund_list(input('post.'));
            $arr = $Recharge->get_finance_tk(input('post.'));
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }

        $acc_list = OpAccount::field('id,name_id')->select();
        $channel = Channel::field('id,name')->select();
        $cu_list = Customer::field('id,name')->select();
        $media_list = $user->get_role_list('14,19');

        $data = ['acc_list' => $acc_list,'channel'=>$channel,'cu_list'=>$cu_list,'media_list'=>$media_list];
        return view('', $data);
    }
   
    /*
     * 
     *   */
    
    //账号退款驳回
    public function get_buohui_refund(){
        if(request()->post()&&input('t')=='json'){
            $data['id'] = input('post.id');
            $data['reject'] = input('post.reject');
            $data['status'] = -1;
            $data['update_time'] = time();
            $data['md5_audit_proof_url'] = '';
            $data['md5_screenshot_url'] = '';
            $r = Recharge::find(input('post.id'));
            
            Db::startTrans();
            try {
                Db::name("recharge")->save($data);
                // 提交事务
                Db::commit();
                log_add(2, '财务驳回操作');
                //发送消息
                get_msg_bh_info(4,$r['media_id'],'',$r['currency']);
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
    }
   
  
    //账号退款 出纳确认
    public function cashier_audit(){
        if(request()->isPost() && input('t')=='json'){
                /* if(empty(input('post.refund_url'))){
                    return json(['code' => 0, 'msg' => '请上传凭证']);
                } */
                
                $data['id'] = input('post.id');
                $data['status'] = 1;
                $data['audit_proof_url'] = input('post.audit_proof_url');
                $data['audit_id'] = session('uid');
                $data['update_time'] = time();
                $r = Recharge::find(input('post.id'));
                // 判断图片是否重复
                if(!empty($data['audit_proof_url'])){
                    $data['md5_audit_proof_url'] = md5_file($data['audit_proof_url']);
                }  
                
                $validate = \think\facade\Validate::rule([
                    'audit_proof_url|凭证图片' => 'require',
                    'md5_audit_proof_url|凭证图片'  => 'require|unique:recharge',
                ]);
                $d = input('post.');
                $d['md5_audit_proof_url'] = md5_file($data['audit_proof_url']);
                if(!$validate->check($d)){
                    // 验证失败 输出错误信息
                    return json(['code' => 0, 'msg' => $validate->getError()]);
                }
                
            // 启动事务
            Db::startTrans();
            try {
                // Db::name('recharge')->where('id',input('post.pid'))->inc('refund',$r['currency']*1)->update();
                
                Db::name('recharge')->save($data);
                //账号币退款成功，跟新客户备款金额
                Db::name('customer')->where('id',$r['customer_id'])->inc('prepare_money', $r['amount']*1)->update();
                //账号币退款成功，跟新客户账户币累计
                Db::name('customer')->where('id', $r['customer_id'])->dec('total_acc_recharge', $r['currency']*1)->update();
                //退款成功，同步财务端口管理
                $this->sync_tk_data($r,$r['currency']);
                // 提交事务
                Db::commit();
                log_add(2, '财务出纳确认操作');
                
                //发送消息
                $cu = Customer::find($r['customer_id']); 
                get_msg_info(6,$r['media_id'].'7',$cu['name'],$r['currency']);
                
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            } 
    
        }else{
            // $r = Recharge::find(input('get.id'));
            $rs = recharge::alias('r')
            ->field('r.*,ch.name channel_name,acc.name_id,cu.name customer_name')
            ->join('channel ch','r.channel_id = ch.id',"LEFT")
            ->join('op_account acc','r.op_account_id = acc.id',"LEFT")
            ->join('customer cu','r.customer_id = cu.id',"LEFT")
            ->where('r.id',input('get.id'))->find();
            View::assign('rs',$rs);
            // View::assign('r',$r);
            return view();
        }
    }
     //账户退款成功，同步到端口管理
     function sync_tk_data($data,$currency){
        $da['type'] = 3;
        $da['create_time'] = time();
        $da['op_account_id'] = $data['op_account_id'];
        $da['rebate'] = $data['channel_rebate'];
        $da['currency'] = '-'.$currency;
        $money = zhb_cny($currency,$data['channel_rebate']);
        $da['amount'] = '-'.$money;
        $da['channel_id'] = $data['channel_id'];
        $r = ChannelRecharge::where('channel_id',$data['channel_id'])->order('create_time desc')->find();
        $da['yue_amount'] = $r['yue_amount'] + $money;
        $da['yue_currency'] = $r['yue_currency'] + $currency;
        ChannelRecharge::create($da);
    }

     //账户退款回滚
     public function get_huigun_refund(){
        if(request()->isPost() && input('t')=='json'){
            $id = input('id');
            $r = Recharge::find($id);
            // 启动事务
            Db::startTrans();
            try {
                // 减去客户备款
                Db::name('customer')->where('id', $r['customer_id'])->dec('prepare_money', $r['amount'])->update();
                // 加上 账户币累计
                Db::name('customer')->where('id', $r['customer_id'])->inc('total_acc_recharge', $r['currency'])->update();
                $data['status'] = 0;
                $data['id'] = $id;
                $data['md5_audit_proof_url'] = '';
                $data['md5_screenshot_url'] = '';
                Db::name("recharge")->update($data);
                // 提交事务
                Db::commit();
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }

        }
     }

    //驳回
    public function reject()
    {
        Db::startTrans();
        $Recharge = new Recharge();
        if (request()->isPost() && input('t') == 'json') {
            $data = input("post.");
            $r = $Recharge->where('id', $data["id"])->find();
            $reject = $Recharge->where('id', $data["id"])->value('reject');
            if (!empty($reject)) {
                $data['reject'] = $reject . ',' . $data['reject'];
            }
            $data['status'] = -1;
            $data['audit_id'] = session('uid');
            $data['update_time'] = time();
            $data['md5_audit_proof_url'] = '';
            $data['md5_screenshot_url'] = '';
            if ($r['type'] == 3) {
                $data['accountant_id'] = 0;
            }
            try {
                Db::name('recharge')->save($data);
                //3客户退款
                if ($r['type'] == 3) {
                    Db::name('customer')->where('id', $r['customer_id'])->inc('prepare_money', (float)$r['amount'])->update();
                    Db::name('customer')->where('id', $r['customer_id'])->dec('frozen_money', (float)$r['amount'])->update();
                    
                }
                // 提交事务
                Db::commit();
                log_add(2, '财务驳回');
                //发送消息
                $cu = Customer::find($r['customer_id']);
                get_msg_bh_info($r['type'],$r['media_id'],$cu['name'],$r['amount']);
                
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }

        }

    }
    // 会计确认客户退款
    public function get_kj_verify(){
        if(request()->isPost() && input('t')=='json'){
            $data['id'] = input('post.id');
            $data['accountant_id'] = session('uid');
            try {
                Recharge::update($data);
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Throwable $th) {
                //throw $th;
                return json(['code' => 0, 'msg' => $th->getMessage()]);
            }
        }
    }
    //出纳确认通过
    public function audit()
    {
        Db::startTrans();
        if (request()->isPost() && input('t') == 'json') {
            $data = input('post.');
            // 判断图片是否重复
            if(!empty($data['audit_proof_url'])){
                $data['md5_audit_proof_url'] = md5_file($data['audit_proof_url']);
            }   
            
            $validate = \think\facade\Validate::rule([
                'audit_proof_url|凭证图片' => 'require',
                'md5_audit_proof_url|凭证图片'  => 'require|unique:recharge'
            ]);
            if(!$validate->check($data)){
                // 验证失败 输出错误信息
                return json(['code' => 0, 'msg' => $validate->getError()]);
            }
            
            $r = Db::name('recharge')->where('id', $data["id"])->find();
            $data['status'] = 1;
            $data['audit_id'] = session('uid');
            $data['oper_name'] = session('info.username');
            $data['update_time'] = time();
            try {
                Db::name('recharge')->strict(false)->save($data);
                if($r['type'] ==1){
                    $c = Db::name('customer')->where('id', $r['customer_id'])->inc('prepare_money', $r['amount']*1)->update();
                    //客户打款金额累计
                    Db::name('customer')->where('id', $r['customer_id'])->inc('total_recharge', $r['amount']*1)->update();
                    // 提交事务
                    Db::commit();
                    log_add(2, '财务出纳客户打款操作');
                    //发送消息
                    $cu = Customer::find($r['customer_id']);
                    get_msg_info(3,$r['media_id'].'7',$cu['name'],$r['amount']);
                    
                    return json(['code' => 1, 'msg' => '提交成功']);
                }elseif ($r['type'] ==2){
                    //充值成功，扣除客户备款金额里的余额
                    Db::name('customer')->where('id', $r['customer_id'])->dec('prepare_money', $r['amount']*1)->update();
                    //账户币累计充值
                    Db::name('customer')->where('id', $r['customer_id'])->inc('total_acc_recharge', $r['currency']*1)->update();
                    //账户充值成功，同步到端口管理
                    $this->sync_data($r);
                    // 提交事务
                    Db::commit();
                    log_add(2, '财务出纳账户充值操作');
                    //发送消息
                    $opa = OpAccount::find($r['op_account_id']);
                    $cu = Customer::find($r['customer_id']);
                    get_msg_info(4,$r['media_id'].'7',$cu['name_id'],$r['currency']);
                    return json(['code' => 1, 'msg' => '提交成功']);
                }elseif ($r['type'] ==3){
                    //客户退款
                    if (!$this->get_cu_refund($r['customer_id'], $r['amount'])) {
                        Db::rollBack();
                        return json(['code' => 0, 'msg' => '客户余额不足，退款失败']);
                        
                    }else{
                        //客户退款成功，扣除客户冻结金额里的余额
                        Db::name('customer')->where('id', $r['customer_id'])->dec('frozen_money', $r['amount']*1)->update();
                        //客户退款成功,更新累计打款
                        Db::name('customer')->where('id', $r['customer_id'])->dec('total_recharge', $r['amount']*1)->update();
                        // 提交事务
                        Db::commit();
                        log_add(2, '财务出纳客户退款操作');
                        //发送消息
                        $cu = Customer::find($r['customer_id']);
                        get_msg_info(7,$r['media_id'].'7',$cu['name'],$r['amount']);
                        return json(['code' => 1, 'msg' => '提交成功']);
                    } 
                }
            } catch (\Exception $e) {
                Db::rollBack();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }

        } else {
            $re = Recharge::where('id',input('get.id'))->find();
            $rs = Customer::find($re['customer_id']);
            $gs_bank = Db::name('account')->where('id',$re['account_bank_id'])->find();
            $arr['channel_name'] = Channel::where('id',$re['channel_id'])->value('name');
            $arr['acc_name'] = OpAccount::where('id',$re['op_account_id'])->value('name_id');
            View::assign("rs",$rs);
            View::assign("re",$re);
            View::assign("gs_bank",$gs_bank);
            View::assign("arr",$arr);
            return view();
        }

    }

    //客户退款时判断余额是否 足够
    function get_cu_refund($cu_id, $amount)
    {
        $Customer = new Customer();
        $m = $Customer->where('id', $cu_id)->value('frozen_money');
        if ($m < $amount) {
            return false;
        } else {
            return true;
        }
    }


    //账户充值时判断客户的金额是否 足够
    function get_acc_re($cu_id, $amount)
    {
        $Customer = new Customer();
        $prepare_money = $Customer->where('id', $cu_id)->value('prepare_money');
        if ($prepare_money*1 >= $amount*1) {
            return true;
        } else {
            return false;
        }
    }
    //账户充值成功，同步到端口管理
    function sync_data($data){
        $da['type'] = 2;
        $da['create_time'] = $data['create_time'];
        $da['op_account_id'] = $data['op_account_id'];
        $da['rebate'] = $data['channel_rebate'];
        $da['currency'] = $data['currency'];
        $da['amount'] = $data['amount'];
        $da['channel_id'] = $data['channel_id'];
        $r = ChannelRecharge::where('channel_id',$data['channel_id'])->order('create_time desc')->find();
        $da['yue_amount'] = $r['yue_amount'] - $data['amount'];
        $da['yue_currency'] = $r['yue_currency'] - $data['currency'];
        ChannelRecharge::create($da);
    }
   
    /* 
     * 回款管理
     *  */
    public function return_money(ReturnedMoney $ReturnedMoney,User $user){
       
        if(request()->post()&& input('t')=='json'){ 
            $arr = $ReturnedMoney->finance_return_money_list(input('post.'));
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }else{
            //获取客户列表
            $cu_list = Customer::where('status',1)->field('id,name')->select();
            $m_list = $user->get_role_list('14,19');

            View::assign('cu_list',$cu_list);
            View::assign('m_list',$m_list);
            return view();
        }
        
    }
    //回款驳回
    function get_return_moner_buohui(){
        if(request()->post()&& input('t')=='json'){
            $data = input('post.');
            $data['status'] = 0;
            $data['accountant_id'] = 0;
            $rs = ReturnedMoney::update($data);
            if($rs){
                log_add(2, '财务驳回');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 0, 'msg' => '提交失败']);
            }
        }
    }
    
    //回款  出纳确认
    public function return_money_cashier(){
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            $data['status'] = 3;
            $data['audit_id'] = session('uid');
            $data['update_time'] = time();
            // 启动事务
            Db::startTrans();
            try {
                $da['is_advance'] = 2;
                $pid = ReturnedMoney::where('id',$data['id'])->value('pid');
                Db::name('recharge')->where('id',$pid)->save($da);
                unset($data['file']);
                Db::name('returned_money')->save($data);
                // 提交事务
                Db::commit();
                log_add(2, '财务出纳确认');
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            $rs = ReturnedMoney::where('id',input('get.id'))->with(['recharge','user','customer','account'])->find();
            
            View::assign('rs',$rs);
            return view();
        }
    }
    
   //月度统计
   public function consume_stat(){
       $ViewItemInfo = new ViewItemInfo();
       $ViewItemsInfo = new ViewItemsInfo();
       if(request()->isPost()&&input('t')=='json'){
           $arr = $ViewItemsInfo->consume_list(input('post.')); 
           
           return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
       }else{
           $this->get_opaccount_info();
           //获取媒介 
           $media_list = $this->get_user_info(14);
           //获取运营
           $operate_list = $this->get_user_info(3);
           View::assign('media_list',$media_list);
           View::assign('operate_list',$operate_list);
           return view();
       }
   }
   
   
    
   //获取账户ID
   function get_opaccount_info(){
       $list = OpAccount::field('id,name,name_id')->select();
       
       View::assign('OpAccount_list',$list);
   }
   //获取媒介14，运营3
   function get_user_info($type=3){
       if($type == 14){
            $wh[] = ['role_id','in',[14,19]];
       }else{
            $wh[] = ['role_id','in',[3,20,18]];
       }
       $list = User::field('id,username')->where($wh)->select();
       return $list;
   }
    
    //账户消耗详情
    public function stat_consume_info(){ 
        if(request()->isPost()&&input('t')=='json'){
            $data = input('post.');
            if($data['time'] == 0){
                $t = date("Y-m-01",time());
                $t1 = strtotime($t);
                $t2 = strtotime("$t +1 month -1 day");
                $wh[] = ['time','between',[$t1,$t2]];
            }else{
                $t = date("Y-m-01",$data['time']);
                $t2 = strtotime("$t +1 month -1 day");
                $wh[] = ['time','between',[$data['time'],$t2]];
            }
            
            $wh[] = ['items_id','=',$data['items_id']];
            $wh[] = ['op_account_id','=',$data['op_account_id']];
            $list = ItemConsume::with(['operate','opaccount'])->where($wh)->order('time')->select();
            
            return json(['code'=>0,'msg'=>'','count'=>0,'data'=>$list]);   
        }else{
            $arr['op_account_id'] = input('get.op_account_id');
            $arr['items_id'] = input('get.items_id');
            $arr['time'] = strtotime(input('get.t'));
           
            View::assign('arr',$arr);
            return view();
        }
        
    }
    //账户充值详情
    public function stat_recharge_info(){
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            if($data['time'] == 0){
                $t = date("Y-m-01",time());
                $t1 = strtotime($t);
                $t2 = strtotime("$t +1 month -1 day");
                $wh[] = ['create_time','between',[$t1,$t2]];
            }else{
                $t = date("Y-m-01",$data['time']);
                $t2 = strtotime("$t +1 month -1 day");
                $wh[] = ['create_time','between',[$data['time'],$t2]];
                
            }
            
            $wh[] = ['items_id','=',$data['items_id']];
            $wh[] = ['op_account_id','=',$data['accitem_id']];
            $wh[] = ['status','=',1];
            $wh[] = ['type','=',2];
            $list = Db::name('view_re_info')->where($wh)->order('create_time')->select();
            
            return json(['code'=>0,'msg'=>'','count'=>0,'data'=>$list]);
        }else{
            $arr['accitem_id'] = input('get.id');
            $arr['time'] = strtotime(input('get.t'));
             
            View::assign('arr',$arr);
            return view();
        }
    }
    
    
    //账户退款明细
    public function stat_acc_refund_info(){
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            
            if($data['time'] == 0){
                $t = date("Y-m-01",time());
                $t1 = strtotime($t);
                $t2 = strtotime("$t +1 month -1 day");
                $wh[] = ['create_time','between',[$t1,$t2]];
            }else{
                $t = date("Y-m-01",$data['time']);
                $t2 = strtotime("$t +1 month -1 day");
                $wh[] = ['create_time','between',[$data['time'],$t2]];
            }
        
            $wh[] = ['op_account_id','=',$data['op_account_id']];
            $wh[] = ['items_id','=',$data['items_id']];
            $wh[] = ['status','=',1];
            $wh[] = ['type','=',4];
            $list = Db::name('view_re_info')->where($wh)->order('create_time')->select();
        
            return json(['code'=>0,'msg'=>'','count'=>0,'data'=>$list]);
        }else{
            $arr['items_id'] = input('get.id');
            $arr['op_account_id'] = input('get.op_account_id');
            $arr['time'] = strtotime(input('get.t'));
             
            View::assign('arr',$arr);
            return view();
        }
    }
   
    
    /* 
     * 账户进出账明细
     * 
     *  */
    public function account_money_info(){
        if(request()->isPost()&&input('t')=='json'){
            $acc_id= 1;
            $wh[] = ['status','=',1];
            $wh[] = ['type','=',2];
            $wh[] = ['op_account_id','=',$acc_id];
            $list = Recharge::where($wh)->field('id,amount,currency,type,practical_currency,items_id,create_time')->order('create_time desc')->select()->toArray();
             return json(['code'=>0,'msg'=>'','count'=>0,'data'=>$list]);
        }else{
            return view();
        }  
    }
    
    //账户 充值回滚
    public function rollback(){


        if(request()->isPost() && input('t')=='json'){
            $id = input('post.id');
            $rs = Recharge::find($id);
            // 启动事务
            Db::startTrans();
            try {
                $data['md5_audit_proof_url'] = '';
                $data['md5_screenshot_url'] = '';
                $data['status'] = 0;
                Db::name('recharge')->where('id',$id)->update($data);
                Db::name('customer')->where('id', $rs['customer_id'])->inc('prepare_money', $rs['amount']*1)->update();
                Db::name('customer')->where('id', $rs['customer_id'])->dec('total_acc_recharge', $rs['currency']*1)->update();
                // 提交事务
                Db::commit();
                return json(['code' => 1, 'msg' => '提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }
    }
    
    
    //消耗列表
    public function consumes_list(ItemConsume $ItemConsume){
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            if(isset($data['uid']) && !empty($data['uid'])){
                $wh[] = ['ic.operation_id','=',$data['uid']];
            }
            if(isset($data['op_account_id']) && !empty($data['op_account_id'])){
                $wh[] = ['ic.op_account_id','=',$data['op_account_id']];
            }
            if(isset($data['is_operate']) && !empty($data['is_operate'])){
                $wh[] = ['ic.is_operate','=',$data['is_operate']];
            }
            if(isset($data['channel_id']) && !empty($data['channel_id'])){
                $wh[] = ['acc.channel_id','=',$data['channel_id']];
            }
            if(isset($data['mid']) && !empty($data['mid'])){
                $wh[] = ['m.id','=',$data['mid']];
            }
            if(isset($data['customer_id']) && !empty($data['customer_id'])){
                $wh[] = ['c.id','=',$data['customer_id']];
            }
            if(isset($data['time']) && !empty($data['time'])){ 
                $time = explode('&',$data['time']);
                $t1 = strtotime($time[0]);
                $t2 = strtotime($time[1]);
                $wh[] = ['ic.time','between',[$t1,$t2]];
            }else{
                $t = strtotime('-30 day');
                $wh[] = ['ic.time','between',[$t,time()]];
            }
            $wh[] = ['ic.currency','>',0];
            $list = $ItemConsume->alias('ic')
            ->field('ic.*,u.username operate_name,acc.name_id opaccount_name,hy.name hy_name,ch.name channel_name,m.username media_name,c.name customer_name')
            ->join('user u','ic.operation_id = u.id','LEFT')
            ->join('op_account acc','ic.op_account_id = acc.id','LEFT')
            ->join('channel ch','acc.channel_id = ch.id','LEFT')
            ->join('industry hy','acc.industry_id = hy.id','LEFT')
            ->join('items i','ic.items_id = i.id','LEFT')
            ->join('customer c','i.customer_id = c.id','LEFT')
            ->join('user m','c.user_id = m.id','LEFT')
            ->where($wh)->order('ic.time desc,ic.operation_id')->page($data['page'],$data['limit'])->select();
            $cnt = $ItemConsume->alias('ic')
            ->join('op_account acc','ic.op_account_id = acc.id','LEFT')
            ->join('channel ch','acc.channel_id = ch.id','LEFT')
            ->join('items i','ic.items_id = i.id','LEFT')
            ->join('customer c','i.customer_id = c.id','LEFT')
            ->join('user m','c.user_id = m.id','LEFT')
            ->where($wh)->count('ic.id');
            return json(['code'=>0,'msg'=>'','count'=>$cnt,'data'=>$list]);
        }else{
            $wh[] =['role_id','in','3,20,18'];
            $User_list = User::field('id,username')->where($wh)->select();
            $w[] =['role_id','in','14,19'];
            $m_list = User::field('id,username')->where($w)->select();
            $acc_list = OpAccount::field('id,name_id')->select();
            $cu_list = Channel::field("id,name")->select();
            $kh_list = Customer::field("id,name")->select();

            View::assign('kh_list',$kh_list);
            View::assign('cu_list',$cu_list);
            View::assign('User_list',$User_list);
            View::assign('acc_list',$acc_list);
            View::assign('m_list',$m_list);
            return view();
        }
    }
    //消耗列表修改
    public function get_save(){
        if(request()->isPost() && input('t') == 'json'){  
            $data = input('post.data');
            $s = '/^-?[0-9]+(.[0-9]{1,2})?$/';
            if (!preg_match($s, $data[1])) {
                return json(['code' => 0, 'msg' => '请输入有效的值']);
            }
            $da['id'] = $data[0];
            $da[$data[2]] = $data[1];
            $rs = ItemConsume::update($da);
            if($rs){
                log_add(2, '财务会计修改');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 0, 'msg' => '提交失败']);
            }
        }
    }
    
    
    //端口管理
    public function channel(ChannelRecharge $ChannelRecharge){
        if(request()->isPost() && input('t') == 'json'){
            $arr = $ChannelRecharge->get_list(input('post.'));
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }
        $ch_list = Channel::field("id,name")->select();

        View::assign("ch_list",$ch_list);
        return view();
    }
    //添加端口打款
    public function add_channel_recharge(ChannelRecharge $ChannelRecharge){
        if(request()->isPost() && input('t') == 'json'){
            $rs = $ChannelRecharge->add(input('post.'));
            if($rs === true){
                log_add(1, '财务端口打款');
                return json(['code' => 1, 'msg' => '提交成功']);
            }else{
                return json(['code' => 0, 'msg' => $rs]);
            }
        }
        $ch_list = Channel::field("id,name")->select();
        if(request()->isGet() && input('id') > 0){
            $rs = $ChannelRecharge->find(input("get.id"));
            View::assign("rs",$rs);
        }

        View::assign("ch_list",$ch_list);
        return view();
    }
    
    //转账列表
    public function list_transfer(AccTransfer $AccTransfer){
        if(request()->isPost() && input('t')=='json'){
            $arr = $AccTransfer->get_finance_list(input('post.'));
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }
        $w['jindu'] = 5;
        $w['status'] = 1;
        $w['is_banned'] = 1;
        $acc_list = OpAccount::field('id,name_id')->where($w)->select();
        
        $wh[] = ['role_id','in','19,14'];
        $media_list = User::field('id,username')->where($wh)->select();
        View::assign('media_list',$media_list);
        View::assign('acc_list',$acc_list);
        return view();
    }
    
    //转账驳回
    public function transfer_reject(AccTransfer $AccTransfer){
        if(request()->isPost() && input('t')=='json'){
            $r = $AccTransfer->get_transfer_reject(input('post.'));
            
            if($r == 1){
                log_add(6,'驳回账户转账');
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>'提交失败']);
            }
        }
    }
    //转账确认
    public function qr_transfer(AccTransfer $AccTransfer){
        if(request()->isPost() && input('t')=='json'){
            $r = $AccTransfer->get_qr_transfer(input('post.'));
            if($r === 1){
                log_add(2,'出纳确认账户转账');
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>'提交失败']);
            }
        }
        $wh[] = ['at.id','=',input('get.id')];
        $rs = AccTransfer::alias('at')
        ->field('at.*,acc.name_id in_name_id,acc2.name_id out_name_id')
        ->join('op_account acc','at.in_acc = acc.id','LEFT')
        ->join('op_account acc2','at.out_acc = acc2.id','LEFT')
        ->where($wh)->find();

        View::assign('rs',$rs);
        return view();
    }

    // 客户资金明细
    public function customer_mingxi(Recharge $Recharge){
        if(request()->isPost() && input('t')=='json'){
            $list = $Recharge->get_cu_zijin_mingxi(input("post."));
            return json(['code'=>0,'msg'=>'','data'=>$list]);
        }
        return view();
    }
    
    //修改客户退款备注
    public function save_cu_refund_note(){
        if(request()->isPost() && input('t')=='json'){
            $data = input("post.");
            try {
                Recharge::update($data);
                return json(['code'=>1,'msg'=>'提交成功']);
            } catch (\Throwable $th) {
                //throw $th;
                return json(['code'=>0,'msg'=>$th->getMessage()]);
            }
            
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    //报销管理

    public function claim(){
        
        $this->user_list();
        return view();
    }

    
    //报销列表
    public function list_claim(){
        $Claim = new Claim();
        if(request()->isPost() && input('t') == 'json'){
        
            $arr = $Claim->list_caiwu_daibaoxiao(input('post.'));
        
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
 
        }
    }
    //申请人列表
    public function user_list(){
        $user = new User();
        $list = $user->select();
        View::assign('user_list',$list);
    }

    //驳回申请
    public function bohui_apply()
    {
        $Claim = new Claim();
        if (request()->isPost() && input('t') == 'json') {
            $id = input('post.id');
            $str = input('post.str');
            $note = $Claim->where('id', $id)->value('note');
            $data['status'] = 0;
            $data['note'] = $note.','.$data['note'];
            $rs = $Claim->where('id',$id)->save($data);
            if($rs === 1){
                log_add(2,'驳回申请操作');
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>$rs]);
            }
        }
    }

    //财务报销审核
    public function audit_pass(){
        $Claim = new Claim();
        if(request()->isPost() && input('t') == 'json'){
            $id = input('post.id');
            $data["accountant_id"] = session('uid');
            $data["accountant_name"] = session('info.username');
            
            $rs = $Claim->where('id',$id)->save($data);
            if($rs === 1){
                log_add(2,'财务会计审核操作');
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>$rs]);
            }
        }
    }
    //财务出纳确认
    public function cashier_pass(){
        $Claim = new Claim();
        if(request()->isPost() && input('t') == 'json'){
            $data = input('post.');
            $data["audit_id"] = session('uid');
            $data["audit_name"] = session('info.username');
            $data["status"] = 3;
            $rs = $Claim->save_cashier($data);
            if($rs === 1){
                log_add(2,'财务出纳审核操作');
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>$rs]);
            }
        }else{
            
            $rs = $Claim->get_cashier_user_info(input('id'));
            View::assign('rs',$rs);
            return view();
        }
    }
    
    /**
     * 赔付记录
     */
    public function paid()
    {
        return view();
    }
    
    //赔付列表
    public function list_paid(){
        $Recharge = new Recharge();
        if(request()->isPost() && input('t')=='json'){
            $arr = $Recharge->get_list_paid(input('post.'));
            return json(['code'=>0,'msg'=>'','count'=>$arr['cnt'],'data'=>$arr['list']]);
        }
    } 
    
    //赔付会计审核
    public function audit_paid(){
        $Recharge = new Recharge();
        if(request()->isPost() && input('t') == 'json'){
            $data['is_accountant'] = 1;
            $data['accountant_id'] = session('uid');
            $data['accountant_name'] = session('info.username');
            $rs = $Recharge->where('id',input('post.id'))->save($data);
            if($rs){
                log_add(2,'财务会计审核操作');
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>$rs]);
            }
        }else{
            $wh[] = ['r.id','=',input('get.id')];
            $wh[] = ['r.is_paid','=',1];
            $rs = $Recharge->alias('r')
            ->field('r.*,ch.name channel_name,ch.rebate channel_rebate,acc.name account_name,cu.name customer_name,u.username media_name,uu.username operate_name')
            ->leftJoin('channel ch','r.channel_id = ch.id')
            ->leftJoin('op_account acc','r.op_account_id = acc.id')
            ->leftJoin('customer cu','r.customer_id = cu.id')
            ->leftJoin('user u','r.media_id = u.id')
            ->leftJoin('user uu','r.operate_id = uu.id')
            ->where($wh)->find();
            View::assign("rs",$rs);
            return view();
        }
    }
    
    //赔付出纳确认
    public function cashier_paid(){
        $Recharge = new Recharge();
        // 启动事务
        Db::startTrans();
        if(request()->isPost() && input('t') == 'json'){
            $data = input('post.');
            $data['status'] = 1;
            $data['audit_id'] = session('uid');
            $data['audit_name'] = session('info.username');
            $r = $Recharge->where('id',$data['id'])->find();
            if(($r['type'] == 2 || $r['type'] == 3) && empty($data['audit_proof_url'])){
                return json(['code'=>0,'msg'=>'凭证不能为空']);
            }
            try{
                //赔付客户
                if($r['type'] == 1){
                    //赔付到客户备款
                    Db::name('customer')->where('id', $r['customer_id'])->inc('prepare_money', $r['amount'])->update();
                }elseif ($r['type'] == 2){
                    //赔付到账户
                    Db::name('op_account')->where('id', $r['op_account_id'])->inc('balance', $r['currency'])->update();
                }
                
                Db::name('recharge')->save($data);
                // 提交事务
                Db::commit();
                log_add(2,'财务出纳确认操作');
                return json(['code'=>1,'msg'=>'提交成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
            
        }else{
            $wh[] = ['r.id','=',input('get.id')];
            $wh[] = ['r.is_paid','=',1];
            $rs = $Recharge->alias('r')
            ->field('r.*,ch.name channel_name,ch.rebate channel_rebate,acc.name account_name,cu.name customer_name,u.username media_name,uu.username operate_name')
            ->leftJoin('channel ch','r.channel_id = ch.id')
            ->leftJoin('op_account acc','r.op_account_id = acc.id')
            ->leftJoin('customer cu','r.customer_id = cu.id')
            ->leftJoin('user u','r.media_id = u.id')
            ->leftJoin('user uu','r.operate_id = uu.id')
            ->where($wh)->find();
            View::assign("rs",$rs);
            return view();
        }
    }
    
    
    
    

}